#include <iostream>
#include <time.h>
#include <stdexcept>

#ifdef _CONSOLE
#else
#include <SFML/Graphics.hpp>
#include "utils/gui/Form.h"
#include "views/concrete/graphic/GameplayView.h"
#endif

#include "controller/ApplicationController.h"
#include "utils/Events.h"

int main()
{
	srand((unsigned int) time(NULL));

#ifdef _CONSOLE
	std::cout << "Tryb konsolowy" << std::endl;
	Controllers::GameplayController gameplay_controller;
	gameplay_controller.startGame();
	return 0;
#else
	sf::RenderWindow App(sf::VideoMode(800, 600), "Cluedo");
	App.SetFramerateLimit(60);
	App.UseVerticalSync(true);

	const sf::Input& Input = App.GetInput();
	boost::signal<void (sf::Event)> AppEvent;
	Utils::GUI::Form Form(App);

	Controllers::ApplicationController application_controller(&Form);
	application_controller.startApp();
	
	while (App.IsOpened())
	{
		sf::Event Event;
		Utils::AppLoopEvent AppLoopEvent;

		while (Utils::AppLoopEventsQueue::getInstance()->getEvent(AppLoopEvent))
		{
			try
			{
				AppLoopEvent();
			}
			catch (Domain::Helpers::NetworkException& e)
			{
				application_controller.handleException(e);
			}
#ifndef _DEBUG
			catch (std::exception& e)
			{
				application_controller.handleException(e);
			}
#endif
		}
		while (App.GetEvent(Event))
		{
			if (Event.Type == sf::Event::Closed || application_controller.isEnded())
			{
				App.Close();
			}
			else if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
			{
				App.Close();
			}
			else if (Event.Type == sf::Event::KeyPressed)
			{
				Form.ConditionalKeyPressed(Event.Key.Code);
			}
			else if (Event.Type == sf::Event::Resized)
			{
				Form.Draw(true);
			}
			else if (Event.Type == sf::Event::MouseMoved)
			{
				Form.MouseMove(Event.MouseMove.X, Event.MouseMove.Y);
			}
			else if (Event.Type == sf::Event::MouseButtonPressed)
			{
				Form.ConditionalClick(Input.GetMouseX(), Input.GetMouseY());
			}
		}
		sf::Sleep(1/90.f);
	}

	return EXIT_SUCCESS;
#endif

}

